package com.yonyou.lxp.account.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.yonyou.lxp.account.BaseActivity;
import com.yonyou.lxp.account.BaseTwoActivity;
import com.yonyou.lxp.account.R;
import com.yonyou.lxp.account.adapter.DataAdapter;
import com.yonyou.lxp.account.adapter.MyAdapter;
import com.yonyou.lxp.account.adapter.MyMsgAdapter;
import com.yonyou.lxp.account.db.DbHelper;
import com.yonyou.lxp.account.entity.ExpenditureInfo;
import com.yonyou.lxp.account.entity.TypeInfo;
import com.yonyou.lxp.account.model.DataModel;
import com.yonyou.lxp.account.utils.Constants;
import com.yonyou.lxp.account.utils.DialogUtils;
import com.yonyou.lxp.account.utils.MsgUtils;
import com.yonyou.lxp.account.utils.Tools;
import com.yonyou.lxp.account.views.time.SlideDateTimeListener;
import com.yonyou.lxp.account.views.time.SlideDateTimePicker;

import org.xutils.DbManager;
import org.xutils.common.task.AbsTask;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import me.drakeet.materialdialog.MaterialDialog;

@ContentView(R.layout.activity_query)
public class QueryActivity extends BaseTwoActivity {

    //    @ViewInject(R.id.rlv_Spending)
    private RecyclerView rlv_Spending;

    //    @ViewInject(R.id.rlv_Income)
    private RecyclerView rlv_Income;


    @ViewInject(R.id.list)
    private ListView listView;

    @ViewInject(R.id.tv_result)
    private TextView tv_result;

    private MyAdapter adapter;

    private DbManager db;

    private List<ExpenditureInfo> list = new ArrayList<>();
    private List<ExpenditureInfo> listMsg = new ArrayList<>();

    private List<TypeInfo> list_0 = new ArrayList<>();
    private List<TypeInfo> list_1 = new ArrayList<>();

    private DataAdapter adapter_0, adapter_1;

    private PopupWindow popupWindow;


    private List<Integer> selTypes = new ArrayList();
    private List<TypeInfo> list_zc = new ArrayList();
    private List<TypeInfo> list_sr = new ArrayList();

    private TextView tv_startTime;
    private TextView tv_endTime;


    private int selType = 0;//查询类型  0本年   1本月   2本周  3自定义

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        db = x.getDb(DbHelper.getDaoConfig());
        init();
        initDialog();
        initData();
        toolbar.setNavigationIcon(null);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_settings:
                        Intent it = new Intent(mContext, SetingActivity.class);
                        startActivityForResult(it, 1008);
                        break;
                    case R.id.action_statistics:
                        Snackbar.make(getWindow().getDecorView(), "敬请期待!", Snackbar.LENGTH_SHORT).show();
//                        it = new Intent(mContext, ChartActivity.class);
//                        startActivity(it);
                        break;
                }
                return true;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case 1008:
                    switch (resultCode) {
                        case 10086:
                            getMsg("0");
                            break;
                        case 10087:
                            getMsg(null);
                            break;
                    }
                    break;
                case 1009://详情页修改后刷新
                    if (_queryType == 5) {//自定义查询
                        sel((long) tv_startTime.getTag(), (long) tv_endTime.getTag(), 1);
                    } else {
                        query(_queryType);
                    }
                    break;
                case 1006://新增收入后刷新
                    if (_queryType == 5) {//自定义查询
                        sel((long) tv_startTime.getTag(), (long) tv_endTime.getTag(), 1);
                    } else {
                        query(_queryType);
                    }
                    break;
                case 1007://新增支出后刷新
                    if (_queryType == 5) {//自定义查询
                        sel((long) tv_startTime.getTag(), (long) tv_endTime.getTag(), 1);
                    } else {
                        query(_queryType);
                    }
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 為了讓 Toolbar 的 Menu 有作用，這邊的程式不可以拿掉
        getMenuInflater().inflate(R.menu.menu_query, menu);
        return true;
    }

    private MyMsgAdapter adapter_msg;

    @Override
    protected void onResume() {
        super.onResume();
        getMsg(null);
    }

    /**
     * 获取消息
     */
    private void getMsg(final String time) {
        x.task().run(new Runnable() {
            @Override
            public void run() {
                listMsg = MsgUtils.getMsg(QueryActivity.this, time);

                List<TypeInfo> data_sr = DataModel.getType(db, mContext, "1");
                if (data_sr != null) {
                    list_sr.addAll(data_sr);
                }
                List<TypeInfo> data_zc = DataModel.getType(db, mContext, "0");
                if (data_sr != null) {
                    list_zc.addAll(data_zc);
                }


                initMsgZcTypeDialog();
                initMsgSrTypeDialog();

                if (listMsg != null && listMsg.size() > 0) {
                    String[] items = new String[listMsg.size()];
                    for (int i = 0; i < listMsg.size(); i++) {
                        items[i] = listMsg.get(i).getE_money();
                    }
                    final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("消息");
                    ListView view = new ListView(mContext);
                    adapter_msg = new MyMsgAdapter(listMsg, getLayoutInflater(), QueryActivity.this);
                    view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                            Toast.makeText(mContext, listMsg.get(i).getE_remarks(), Toast.LENGTH_SHORT).show();
                            _selTypeIndex = i;
                            if ("0".equals(listMsg.get(i).getT_type())) {
                                mDialog_zc.show();
                            } else {
                                mDialog_sr.show();
                            }

                        }
                    });
                    view.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                        @Override
                        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {

                            DialogUtils.showDialog(mContext, "提示", "确定删除吗？", new DialogUtils.MyOnClick() {
                                @Override
                                public void onClick() {
                                    try {
                                        listMsg.remove(i);
                                        adapter_msg.notifyDataSetChanged();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            return true;
                        }
                    });

                    view.setAdapter(adapter_msg);
                    builder.setView(view);
                    builder.setPositiveButton("保存", null);
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    });
                    x.task().post(new Runnable() {
                        @Override
                        public void run() {
                            dialog = builder.create();
                            dialog.show();
                            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    x.task().run(new Runnable() {
                                        @Override
                                        public void run() {
                                            for (ExpenditureInfo info : listMsg) {
                                                if (info.getT_name() == null || info.getT_name().length() <= 0) {
                                                    x.task().post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            Toast.makeText(mContext, "请选择全部收支类型或删除不需要收支", Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                                    return;
                                                }
                                            }

                                            try {
                                                db.saveOrUpdate(listMsg);
                                                x.task().post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
                                                    }
                                                });

                                                dialog.dismiss();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }

                                        }
                                    });
                                }
                            });
                        }
                    });

                }

            }

        });


    }

    private AlertDialog dialog;

    private void initData() {
        x.task().post(new Runnable() {
            @Override
            public void run() {
                setTitle("本周");
                sel(Tools.getMondayOfThisWeek(), Tools.getSundayOfThisWeek(), 0);

                try {
                    List<TypeInfo> data_type_0 = db.selector(TypeInfo.class).where("t_type", "=", "0").findAll();
                    if (data_type_0 != null) {
                        list_0.clear();
                        list_0.addAll(data_type_0);
                    }
                    adapter_0.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }


                try {
                    List<TypeInfo> data_type_1 = db.selector(TypeInfo.class).where("t_type", "=", "1").findAll();
                    if (data_type_1 != null) {
                        list_1.clear();
                        list_1.addAll(data_type_1);
                    }
                    adapter_1.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 条件查询
     */
    private void sel(final long startTime, final long endTime, final int type) {
        x.task().post(new Runnable() {
            @Override
            public void run() {
                try {
                    list.clear();
                    adapter.notifyDataSetChanged();

                    int[] types = new int[selTypes.size()];
                    for (int i = 0; i < selTypes.size(); i++) {
                        types[i] = selTypes.get(i);
                    }
                    List<ExpenditureInfo> data = null;
                    if (type == 0) {
                        data = db.selector(ExpenditureInfo.class).orderBy("e_time", true)
                                .where("e_time", "between", new long[]{startTime, endTime}).findAll();
                    } else {
                        data = db.selector(ExpenditureInfo.class).orderBy("e_time", true)
                                .where("t_id", "in", types)
                                .and("e_time", "between", new long[]{startTime, endTime}).findAll();
                    }
                    if (data != null) {
                        list.addAll(data);
                    }
                    adapter.notifyDataSetChanged();
                    result();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 统计结果
     */
    private void result() {
        double a = 0;//支出
        double b = 0;//收入
        double c = 0; //总计
        for (ExpenditureInfo info : list) {
            if ("0".equals(info.getT_type())) {
                a += Double.parseDouble(info.getE_money());
            } else {
                b += Double.parseDouble(info.getE_money());
            }
        }
        c = b - a;
        tv_result.setText("总计：" + Tools.change(c) + "  收入：" + Tools.change(b) + "  支出：" + Tools.change(a));
    }

    private void init() {
        adapter = new MyAdapter(list, getLayoutInflater(), QueryActivity.this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, ContentActivity.class);
                intent.putExtra("data", list.get(position));
                startActivityForResult(intent, 1009);
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                DialogUtils.showDialog(mContext, "提示", "确定删除吗？", new DialogUtils.MyOnClick() {
                    @Override
                    public void onClick() {
                        try {
                            db.delete(list.get(position));
                            list.remove(position);
                            adapter.notifyDataSetChanged();
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return true;
            }
        });
    }


    private void initDialog() {
        View view = getLayoutInflater().inflate(R.layout.pop_type, null);
        Button btn_sel = (Button) view.findViewById(R.id.btn_sel);
        CheckBox cb_all_spending = (CheckBox) view.findViewById(R.id.cb_all_spending);
        CheckBox cb_all_income = (CheckBox) view.findViewById(R.id.cb_all_income);
        tv_startTime = (TextView) view.findViewById(R.id.tv_startTime);
        tv_endTime = (TextView) view.findViewById(R.id.tv_endTime);

        tv_startTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SlideDateTimePicker.Builder(getSupportFragmentManager())
                        .setListener(new SlideDateTimeListenerImp(tv_startTime))
                        .setInitialDate(new Date())
                        .setMaxDate(new Date())
                        //.setIs24HourTime(true)
                        //.setTheme(SlideDateTimePicker.HOLO_DARK)
                        //.setIndicatorColor(Color.parseColor("#990000"))
                        .build()
                        .show();
            }
        });

        tv_endTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SlideDateTimePicker.Builder(getSupportFragmentManager())
                        .setListener(new SlideDateTimeListenerImp(tv_endTime))
                        .setInitialDate(new Date())
                        .setMaxDate(new Date())
                        //.setIs24HourTime(true)
                        //.setTheme(SlideDateTimePicker.HOLO_DARK)
                        //.setIndicatorColor(Color.parseColor("#990000"))
                        .build()
                        .show();
            }
        });
        btn_sel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<Integer, Boolean> map_1 = adapter_1.getMap();
                for (Integer key : map_1.keySet()) {
                    LogUtil.e(list_1.get(key).getT_name());
                    selTypes.add(list_1.get(key).getT_id());
                }

                Map<Integer, Boolean> map_0 = adapter_0.getMap();
                for (Integer key : map_0.keySet()) {
                    selTypes.add(list_0.get(key).getT_id());
                }
                if (selTypes.size() == 0) {
                    Tools.showToast(mContext, "请选择收支项目");
                    return;
                }
                if (tv_startTime.getText().length() == 0) {
                    Tools.showToast(mContext, "请选择开始时间");
                    return;
                }
                if (tv_endTime.getText().length() == 0) {
                    Tools.showToast(mContext, "请选择结束时间");
                    return;
                }


                sel((long) tv_startTime.getTag(), (long) tv_endTime.getTag(), 1);
                setTitle("自定义");
                popupWindow.dismiss();
            }
        });


        //收入
        rlv_Income = (RecyclerView) view.findViewById(R.id.rlv_Income);
        rlv_Income.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.HORIZONTAL));
        adapter_1 = new DataAdapter(list_1, mContext);
        rlv_Income.setAdapter(adapter_1);

        //支出
        rlv_Spending = (RecyclerView) view.findViewById(R.id.rlv_Spending);
        rlv_Spending.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.HORIZONTAL));
        adapter_0 = new DataAdapter(list_0, mContext);
        rlv_Spending.setAdapter(adapter_0);

        cb_all_spending.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                adapter_0.setAll(isChecked);
            }
        });
        cb_all_income.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                adapter_1.setAll(isChecked);
            }
        });

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
    }

    private int _queryType = 3;//记录查询类型

    @Event(value = {R.id.btn_query_custom, R.id.btn_year, R.id.btn_month, R.id.btn_week, R.id.btn_day, R.id.btn_query_add_income, R.id.btn_query_add_pay})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_query_custom://自定义
                query(5);
                break;
            case R.id.btn_year://本年
                query(1);
                break;
            case R.id.btn_month://本月
                query(2);
                break;
            case R.id.btn_week://本周
                query(3);
                break;
            case R.id.btn_day://今日
                query(4);
                break;
            case R.id.btn_query_add_income://新增收入
                Intent it = new Intent(mContext, IncomeActivity.class);
                startActivityForResult(it, 1006);
                break;
            case R.id.btn_query_add_pay://新增支出
                it = new Intent(mContext, SpendingActivity.class);
                startActivityForResult(it, 1007);
                break;
        }

    }

    /**
     *
     */
    private void query(int type) {
        switch (type) {
            case 5://自定义
                _queryType = 5;
                tv_startTime.setText("");
                tv_endTime.setText("");
                selTypes.clear();
                popupWindow.showAsDropDown(toolbar);
                break;
            case 1://本年
                _queryType = 1;
                setTitle("本年");
                sel(Tools.getCurrYearFirst(), Tools.getCurrYearLast(), 0);
                break;
            case 2://本月
                _queryType = 2;
                setTitle("本月");
                sel(Tools.getFristDay(), Tools.getLastDay(), 0);
                break;
            case 3://本周
                _queryType = 3;
                setTitle("本周");
                sel(Tools.getMondayOfThisWeek(), Tools.getSundayOfThisWeek(), 0);
                break;
            case 4://今日
                _queryType = 4;
                setTitle("今日");
                sel(Tools.getDayStart(), System.currentTimeMillis(), 0);
                break;
        }
    }


    private class SlideDateTimeListenerImp extends SlideDateTimeListener {
        private TextView textView;

        public SlideDateTimeListenerImp(TextView textView) {
            this.textView = textView;
        }

        @Override
        public void onDateTimeSet(Date date) {
            String time = Constants.mFormatter.format(date);
            textView.setText(time);
            textView.setTag(date.getTime());
        }

        @Override
        public void onDateTimeCancel() {
            //Toast.makeText(mContext, "Canceled", Toast.LENGTH_SHORT).show();
        }
    }

    private MaterialDialog mDialog_addtype;

    private void initAddTypeDialog(final int addType) {
        mDialog_addtype = new MaterialDialog(mContext);


        View view = getLayoutInflater().inflate(R.layout.dialog_addtype, null);
        Button btn_addtype = (Button) view.findViewById(R.id.btn_addtype);
        TextView tv_addtype_titile = (TextView) view.findViewById(R.id.tv_addtype_titile);
        final EditText edt_typename = (EditText) view.findViewById(R.id.edt_typename);
        final TypeInfo typeinfo = new TypeInfo();

        if (addType == 1) {
            tv_addtype_titile.setText("新增收入项");
        } else {
            tv_addtype_titile.setText("新增支出项");
        }
        typeinfo.setT_type(addType + "");
        btn_addtype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = (edt_typename.getText() + "").trim();
                if (content.length() > 0) {
                    typeinfo.setT_name(content);
                    try {
                        db.saveOrUpdate(typeinfo);
                        mDialog_addtype.dismiss();
                        if (addType == 1) {
                            refreshType(1);
                        } else {
                            refreshType(0);
                        }
                    } catch (DbException e) {
                        Toast.makeText(mContext, "此项已经存在啦", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(mContext, "收支项不能为空啊", Toast.LENGTH_SHORT).show();
                }

            }
        });

        mDialog_addtype.setView(view);
        mDialog_addtype.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog_addtype.dismiss();
            }
        });

        mDialog_addtype.show();
    }

    private MaterialDialog mDialog_sr;
    private ArrayAdapter<TypeInfo> adapter_sr;

    private void initMsgSrTypeDialog() {
        mDialog_sr = new MaterialDialog(mContext);

        View view = getLayoutInflater().inflate(R.layout.dialog_seltype, null);
        Button btn_addtype = (Button) view.findViewById(R.id.btn_addtype);
        TextView tv_seltype_titile = (TextView) view.findViewById(R.id.tv_seltype_titile);
        ListView lv_type = (ListView) view.findViewById(R.id.lv_type);
        tv_seltype_titile.setText("确定收入类型:");
        btn_addtype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initAddTypeDialog(1);
            }
        });
        lv_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (_selTypeIndex != -1) {
                    listMsg.get(_selTypeIndex).setT_id(list_sr.get(i).getT_id());
                    listMsg.get(_selTypeIndex).setT_name(list_sr.get(i).getT_name());
                    adapter_msg.notifyDataSetChanged();
                }

                mDialog_sr.dismiss();

            }
        });
        adapter_sr = new ArrayAdapter<TypeInfo>(mContext, android.R.layout.select_dialog_item, list_sr);
        lv_type.setAdapter(adapter_sr);

        mDialog_sr.setView(view);
        mDialog_sr.setPositiveButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog_sr.dismiss();
            }
        });
    }

    private MaterialDialog mDialog_zc;
    private ArrayAdapter<TypeInfo> adapter_zc;
    private int _selTypeIndex = -1;

    private void initMsgZcTypeDialog() {
        mDialog_zc = new MaterialDialog(mContext);
        View view = getLayoutInflater().inflate(R.layout.dialog_seltype, null);
        Button btn_addtype = (Button) view.findViewById(R.id.btn_addtype);
        TextView tv_seltype_titile = (TextView) view.findViewById(R.id.tv_seltype_titile);
        ListView lv_type = (ListView) view.findViewById(R.id.lv_type);
        lv_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (_selTypeIndex != -1) {
                    listMsg.get(_selTypeIndex).setT_id(list_zc.get(i).getT_id());
                    listMsg.get(_selTypeIndex).setT_name(list_zc.get(i).getT_name());
                    adapter_msg.notifyDataSetChanged();
                }
                mDialog_zc.dismiss();
            }
        });
        tv_seltype_titile.setText("确定支出类型:");
        btn_addtype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initAddTypeDialog(0);
            }
        });
        adapter_zc = new ArrayAdapter<TypeInfo>(mContext, android.R.layout.select_dialog_item, list_zc);
        lv_type.setAdapter(adapter_zc);

        mDialog_zc.setView(view);
        mDialog_zc.setPositiveButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog_zc.dismiss();
            }
        });
    }

    /**
     * 设置标题
     *
     * @param title
     */
    private void setTitle(String title) {
        toolbar.setTitle("查询-" + title);
    }


    private void refreshType(final int type) {
        x.task().run(new Runnable() {
            @Override
            public void run() {
                if (type == 0) {
                    List<TypeInfo> data_zc = DataModel.getType(db, mContext, "0");
                    if (data_zc != null) {
                        list_zc.clear();
                        list_zc.addAll(data_zc);

                    }
                } else {
                    List<TypeInfo> data_sr = DataModel.getType(db, mContext, "1");
                    if (data_sr != null) {
                        list_sr.clear();
                        list_sr.addAll(data_sr);

                    }
                }

                x.task().post(new Runnable() {
                    @Override
                    public void run() {
                        if (type == 0) {
                            adapter_zc.notifyDataSetChanged();
                        } else {
                            adapter_sr.notifyDataSetChanged();
                        }
                    }
                });
            }
        });

    }

    /**
     * 连续点击两次退出程序;
     */
    private long exitTimeMillis = System.currentTimeMillis();

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTimeMillis == 0 || System.currentTimeMillis() - exitTimeMillis > 1000) {
            exitTimeMillis = System.currentTimeMillis();
            Tools.showToast(mContext, "再按一次退出程序");
            return;
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());//退出
            System.exit(0);
        }
    }
}
